"use server";

import { prisma } from "@/lib/db";
import { handlerAction } from "@/lib/handlerAction";
import { getQueryWhere } from "@/lib/sqlQuery";
import { isJsonString } from "@/lib/utils";
import dayjs from "dayjs";
import { LoginProp } from "../login/page";
import { goesSet } from "@/lib/auth";
import { cookies } from "next/headers";
import admin_config from "@/config/admin_config";
import { User } from "@prisma/client";

export const createPerson = handlerAction<User>(async (form: User) => {
  let { roleList, ...data } = form;
  let temp = "";
  if (roleList) {
    temp = JSON.stringify(roleList);
  }
  const result = await prisma.user.create({
    data: {
      ...data,
      roleList: temp,
    },
  });
  return result;
});
export const updatePerson = handlerAction<User>(async (form: User) => {
  let { id, roleList, ...data } = form;
  let temp = "";
  if (roleList) {
    temp = JSON.stringify(roleList);
  }
  const result = await prisma.user.update({
    where: {
      id: form.id,
    },
    data: {
      ...data,
      roleList: temp,
    },
  });
  return result;
});
export const listPerson = handlerAction<{
  list: User;
  total: number;
}>(async (form: any) => {
  let { page = 1, pageSize = 10, roleList = "", ...others } = form;
  let whereParams = getQueryWhere(others);
  let where = {
    ...whereParams,
  };
  if (roleList) {
    where.roleList = {
      contains: roleList,
    };
  }
  pageSize = Number(pageSize);
  let funs = [
    await prisma.user.findMany({
      skip: (page - 1) * pageSize, // 跳过前 `offset` 条记录
      take: pageSize, // 取 `pageSize` 条
      where,
      orderBy: {
        createdAt: "desc",
      },
    }),
    await prisma.user.count({
      where,
    }),
  ];
  const [result, total] = await Promise.all(funs);
  return {
    list: (result as User[]).map((it) => {
      return {
        ...it,
        roleList: isJsonString(it.roleList || "")
          ? JSON.parse(it.roleList as string)
          : [],
        createdAt: dayjs(it.createdAt).format("YYYY-MM-DD HH:mm:ss"),
      };
    }),
    // list:result,
    total,
  };
});

export const userLogin = handlerAction(async (form: LoginProp) => {
  const cookie = await cookies();
  const result = await prisma.user.findUnique({
    where: {
      name: form.name,
      password: form.password,
    },
    select: {
      id: true,
      name: true,
      roleList: true,
      currentRole: true,
    },
  });
  if (!result) {
    throw new Error("用户名或密码错误");
  }
  const token = await goesSet(result);
  if (token) {
    cookie.set(admin_config.token, token);
    cookie.set("userId", result.id.toString());
    return token;
  }
  return false;
});

export const userLogout = handlerAction(async () => {
  const cookie = await cookies();
  cookie.delete(admin_config.token);
  cookie.delete("userId");
  return true;
});

export const toggleRole = handlerAction(async (form: any) => {
  const result = await prisma.user.update({
    where: {
      id: form.id,
    },
    data: {
      currentRole: form.role,
    },
  });
  return result;
});

// 删除用户
export const userDelete = handlerAction<User>(async (params: User) => {
  return prisma.user.delete({
    where: {
      id: params.id,
    },
  });
});
